<?php
namespace App\Models\Account;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Facades\Request;
use DB;
use \Illuminate\Support\Facades\Input;

use App\Third\Game\SocketClient;

// 后台发送鸡腿日志
class Thew extends  Model{

	protected $table='thew_send_log';

	public function paginate()
    {
    	$perPage = Request::get('per_page', 20);

        $page = Request::get('page', 1);

        $start = ($page-1)*$perPage;

        $tableAccount = $this->table;
        $data = \DB::connection('mysql_bgsi')->table($tableAccount)->skip($page* $perPage)->take($perPage)->get();
        $data = $data->toArray();

        $total = \DB::connection('mysql_bgsi')->table($tableAccount)->count();

        // $data = json_decode($data, true);

        $list = static::hydrate($data);

        $paginator = new LengthAwarePaginator($list, $total, $perPage);

        $paginator->setPath(url()->current());

        return $paginator;
    }

    public static function with($relations)
    {
        return new static;
    }

    public function getConnectionName(){
        return 'mysql_bgsi';
    }

    // 组织发送棘突的消息数据
    public static function orgNotifyData($playerInfo, $extra = []){
        $data = $extra;
        $data['account'] = $playerInfo['account'];
        $data['playerId'] = $playerInfo['playerId'];
        $data['thew'] = $playerInfo['thew'];
        $data['area'] = $playerInfo['area'];
        //$data['ip'] = $areaInfo['ip'];
        //$data['port'] = $areaInfo['ip'];
        return $data;
    }

    // 向游戏发送socket 消息.
    public static function notifyGame($data = []){
        try {
            //if (function_exists("fastcgi_finish_request")) {
            //    fastcgi_finish_request();
            //}   
            if (!$data['playerId'] || !$data['area']) {
            
                \Log::error('send thew data error', [$data]);
                return ;
            }

            \Log::debug('send to game server', [$data['area']]);
            $sock = \App\Models\Area::areaInfo($data['area']);
            //$socket = new SocketClientTianyu($sockConf['host'], $sockConf['port']);
            $socket = new \App\Third\Game\SocketClient($sock['ip'], $sock['port']);
            //file_put_contents('/tmp/xyj', print_r(['notify socket connect' ,$sock->rechargeIp], 1),8);
            $data['msgid'] = $msgid = \Config::get('third.game_socket.thew') ?:0;
            
            $ret = $socket->send($data);
            $defaultSock = null;
            $socket->close($defaultSock);

            $ret && self::notifySave($data);
        }catch(\Exception $e) {
            \Log::error('socket thew exception', [$e->getCode(), $e->getMessage()]);
        }
    }   

    public static function notifySave($data = []){
    }

}
